<?php

/**
 * 核心模版类
 * User: xiaoqiang
 * Date: 15-3-22
 * Time: 下午7:36
 */
use \Library\template\LibPreg;

class LibTemplate extends \LibBase
{

    /**
     * 标签前标识
     * @var string
     */
    public $_afterPrex = "<{";

    /**
     * 标签后标识
     * @var string
     */
    public $_beforePrex = "}>";

    /**
     * 模版变量参数
     * @var array
     */
    public $tplParams = array();

    /**
     * 已解析的模版标签
     * @var array
     */
    public $tagLib = [
        'include',
        'for',
        'foreach',
        'js',
        'css',
        'if',
        'elseif',
        'else',
        'defined',
        'assign',
        'avatar',
        'switch',
        'case',
        'default',
        'lang',
        "img"
    ];

    /**
     * 重新编译模版文件,并删除就文件
     * @param $application
     * @param $template
     */
    public function compile($application, $template)
    {
        $sourceTemplate = $this->getTemlateUpdateTime($application, $template)[1];
        $sContent = file_get_contents($sourceTemplate, FILE_USE_INCLUDE_PATH);
        $sContent = $this->_parse($application, $sContent);
        $sContent = \Library\template\LibTools::parsePrex($sContent);
        //$sContent = preg_replace("\r\n", "", $sContent); //似乎会出问题
        file_put_contents(\Library\template\LibTools::getCacheFileName($application, $template), $sContent);
    }

    /**
     * 引入模版的PHP文件
     * @param $application
     * @param $return
     * @param $template
     * @return string
     */
    public function display($application, $template, $return = false)
    {
        $cacheTemplate = \Library\template\LibTools::getCacheFileName($application, $template);
        if ($return) {
            ob_start();
            include $cacheTemplate;
            $contents = ob_get_contents();
            ob_end_clean();
            return $contents;
        }
        include_once $cacheTemplate;
        return "";
    }

    /**
     * 传数据进入模版
     * @param array() $datas
     */
    public function assign($datas)
    {
        $this->tplParams = array_merge($this->tplParams, $datas);
    }

    /**
     * 获得模版文件上次修改的时间
     * @param $application
     * @param $template
     * @return array
     */
    public function getTemlateUpdateTime($application, $template)
    {
        $templateFile = \Library\template\LibTools::getTemplatePath($application, $template);
        $fileSyncTime = filemtime($templateFile);
        return array($fileSyncTime, $templateFile);
    }


    /**
     * 转换模版标签里面的参数
     * @param $application
     * @param $content
     * @return mixed
     */
    public function _parse($application, $content)
    {
        $result = preg_replace_callback(LibPreg::TEMPLATE_PREX, function ($match) use ($application) {
            $params = $this->_tagFilter($match[0]);
            $tagLib = explode(" ", $params)[0];
            if (in_array($tagLib, $this->tagLib)) { //编译标签
                $method = "parse" . ucfirst($tagLib);
                if (method_exists('\Library\template\LibParse', $method)) {
                    $libParse = \Library\template\LibParse::getInstance();
                    return $libParse->$method($params, $application);
                }
                return "";
            }
            if ($params{0} == "/") { //标签结尾符号<{/if}><{/case}>
                \Library\template\LibTools::filterSpace($params);
                if (preg_match(LibPreg::STRING, $params, $tmp)) {
                    if ($tmp[1] == "case") { //对<{/case}>进行特殊处理
                        return "break;}";
                    }
                    return "}";
                }
            }
            if ($params[0] == "$") { //直接输出变量及默认值的<{$params.data|default=3434}>
                \Library\template\LibTools::filterSpace($params);
                if (preg_match('/^\$[\w|\.]+\|default=[\w|\d]+$/is', $params)) { //使用默认值
                    $tmpArr = explode("|", $params);
                    $default = "";
                    if (preg_match('/^default=(.*)/is', $tmpArr[1], $result)) {
                        $result[1] && $default = $result[1];
                    }
                    $result = \Library\template\LibTools::convertParams($tmpArr[0], false);
                    $result = "echo {$result}";
                    $result .= $default ? "?:" . $default . ";" : ";";
                    return $result;
                }
                if (preg_match_all('/[\+|-|*|\/|\+\+|\-\-|%]+/', $params)) { //使用运算符<{$params.data+$params.time}>
                    $params = preg_replace_callback('/\$[\w|\.]+/', function ($match) {
                        $result = \Library\template\LibTools::convertParams($match[0], false);
                        return $result;
                    }, $params);
                    $params = "echo " . $params . ";";
                    return $params;
                }
                return \Library\template\LibTools::convertParams($params, true);
            }
            return \Library\template\LibTools::format($params); //原样输出字符但替换其中变量
        }, $content);
        return $result;
    }


    /**
     * 标签内容的预处理
     * @param $params
     * @return mixed|string
     */
    private function _tagFilter($params)
    {
        $params = trim($params);
        $params = preg_replace(array('/\s{1,}/is', '/\r\n/is'), " ", $params);
        $params = preg_replace('/\'/', "\"", $params);
        $filter = [
            '=',
            '==',
            '>=',
            '<=',
            '===',
            '>',
            '<'
        ];
        foreach ($filter as $pattern) {
            $params = preg_replace('/(\s*)(?=' . $pattern . ')/', "", $params);
            $params = preg_replace('/(?<=' . $pattern . ')(\s*)/', "", $params);
        }
        return $params;
    }

} 